package com.api.common;


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by rio on 2017/1/17.
 */
@Controller
public  class ResCodeMessageCache implements InitializingBean {
    private Resource[] codeXml;
    public static Map<String, String> ResMessage = new HashMap<String, String>();

    public void setCodeXml(Resource[] codeXml) {
        this.codeXml = codeXml;
    }

    public void afterPropertiesSet() throws Exception {
        for (Resource resource : codeXml) {
            File file = resource.getFile();
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(file);
            Element root = document.getRootElement();
            Element element;
            for (Iterator i = root.elementIterator("Message"); i.hasNext(); ) {
                element = (Element) i.next();
                String code = element.attribute(0).getValue();
                String desc = element.attribute(1).getValue();
                ResMessage.put(code, desc);
            }
        }
    }

    public static String getMessageDesc(String code) {
        return ResMessage.get(code);
    }
}
